import 'dart:io';
import 'dart:typed_data';
import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter_application_1/global.dart';
import 'package:flutter_application_1/request/request.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

// 上传文件
Future<ResultData<String>> upload(file) async {
  // 检查网络
  if (await (new Connectivity().checkConnectivity()) ==
      ConnectivityResult.none) {
    return ResultData(
      code: Code.COMMON_ERROR,
      msg: '网络连接不可用，无法上传',
    );
  }

  MultipartFile? multipartFile;

  if (file is AssetEntity) {
    File? originFile = await file.originFile;
    multipartFile = await MultipartFile.fromFile(originFile!.path);

    // Uint8List? originBytes = await file.originBytes;
    // List<int> imageData = originBytes!.buffer.asInt8List();
    // multipartFile = MultipartFile.fromBytes(imageData);
  } else if (file is MultipartFile) {
    multipartFile = file;
  }

  if (multipartFile != null) {
    FormData formData = new FormData.fromMap({
      'file': multipartFile,
    });

    Dio uploadDio = Dio();

    Response response = await uploadDio.post(
      Global.UPLOAD_API,
      data: formData,
    );

    Map<String, dynamic> data = response.data;

    if (response.statusCode == 200 && data['success']) {
      return ResultData(
        code: response.statusCode,
        data: data['filePath'].toString(),
      );
    } else {
      return ResultData(
        code: response.statusCode,
        msg: data['msg'].toString(),
      );
    }
  } else {
    return ResultData(
      code: Code.COMMON_ERROR,
      msg: '未知的上传文件类型',
    );
  }
}
